package hn.cch.transaction;


import hn.cch.controller.OrderController;
import hn.cch.entity.Order;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

@RocketMQTransactionListener(txProducerGroup = "logger-group")
public class LoggerListener implements RocketMQLocalTransactionListener {

    private static Logger logger = LoggerFactory.getLogger(LoggerListener.class);

    @Autowired
    private LoggerRepository loggerRepository;

    @Autowired
    private LoggerService loggerService;



    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            loggerService.createOrder((String) message.getHeaders().get("txid"), (Order) o);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            logger.error("Exception:{}", e);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        LoggerMessage loggerMessage = loggerRepository.findById((String) message.getHeaders().get("txid")).get();
        if (loggerMessage == null){
            return RocketMQLocalTransactionState.COMMIT;
        }else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
